package com.luocc.inputdemo.watcher

import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import com.luocc.inputdemo.MainActivity

class Watcher1(private val editText: EditText, private val limit: Int, private val TAG: String): TextWatcher {
    private var suitable = true
    private val what = "luo"
    private val editable = editText.editableText
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        Log.d(TAG, "beforeTextChanged")
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        Log.d(
            MainActivity.TAG,
            "onTextChanged: s = $s, start = $start, before = $before, count = $count"
        )
        s?.let {
            suitable = s.length <= limit
            if (!suitable) {
                editable.setSpan(what, start, start + count, 1)
            }
        }
    }

    override fun afterTextChanged(s: Editable?) {
        Log.d(TAG, "afterTextChanged")
        if (!suitable) {
            s?.let {
                // 注意substring的参数范围
                Log.d(TAG, "afterTextChanged: ${editable.getSpanStart(what)}")
                val start = s.substring(0, editable.getSpanStart(what))
                Log.d(TAG, "afterTextChanged: start =  $start")
                val end = s.substring(editable.getSpanEnd(what), s.length)
                Log.d(TAG, "afterTextChanged: end = $end")
                val text = start + end
                // 会继续调用before、on、after
                editText.setText(text)
                editText.setSelection(editable.getSpanStart(what))
            }
        }
    }
}